import 'dart:ui';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:tot_android_flutter/base/BaseController.dart';
import 'package:tot_android_flutter/eneity/AppResponse.dart';
import 'package:tot_android_flutter/utils/log_util.dart';

import '../common/widget/state/view_state.dart';

abstract class BasePageController extends BaseController{
  int curPage = 0;
  int pageSize = 10;
  EasyRefreshController? refreshController;

  void refreshPaging();

  void loadMorePaging();

  void sendRefreshPagingRequest<T>(
      Future<AppResponse<T>> sendRequestBlock, {
        bool bindViewState = true,
        ValueChanged<T>? successBlock,
        VoidCallback? emptyCallback,
        VoidCallback? failCallback,
      }) {
    curPage = 0;
    sendRequestBlock.then((result) {
      if (result.isSuccess()) {
        refreshController?.finishRefresh(IndicatorResult.success);
        if (!result.isEmpty()) {
          curPage++;
          if (successBlock != null) {
            successBlock(result.data!);
          }
        } else {
          if (bindViewState) {
            viewState.value = ViewStateEmpty();
          }else{
            refreshController?.finishRefresh(IndicatorResult.noMore);
          }
          emptyCallback;
        }
      } else {
        refreshController?.finishRefresh(IndicatorResult.fail);
        failCallback;
      }
    }).catchError((e) {
      refreshController?.finishRefresh(IndicatorResult.fail);
      failCallback;
      WanLog.e("sendRefreshPagingRequest catchError====>error:$e");
    });
  }

  void sendLoadMorePagingRequest<T>(
      Future<AppResponse<T>> sendRequestBlock, {
        JudgeNoMoreData<AppResponse<T>>? judgeNoMoreDataBlock,
        ValueChanged<T>? successBlock,
        VoidCallback? emptyCallback,
        VoidCallback? failCallback,
      }) {
    sendRequestBlock.then((result) {
      if (result.isSuccess()) {
        curPage++;
        if (!result.isEmpty()) {
          bool isNoMoreData = (judgeNoMoreDataBlock != null)
              ? judgeNoMoreDataBlock(result)
              : result.noMoreData(pageSize);
          if (!isNoMoreData) {
            refreshController?.finishLoad(IndicatorResult.success);
          } else {
            refreshController?.finishLoad(IndicatorResult.noMore);
          }
        } else {
          refreshController?.finishLoad(IndicatorResult.noMore);
          emptyCallback;
        }
        if (successBlock != null && !result.isEmpty()) {
          successBlock(result.data!);
        }
      } else {
        refreshController?.finishLoad(IndicatorResult.fail);
        failCallback;
      }
    }).catchError((e) {
      refreshController?.finishLoad(IndicatorResult.fail);
      failCallback;
      WanLog.e("sendLoadMorePagingRequest catchError====>error:$e");
    });
  }

}

